<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        input{
            width: 60px;
        }
    </style>
</head>
<body>

    <div class="cart">
        <p>
            <span class="reduce"></span>
            <input type="text" value="2" class="a">
            <span class="add">+</span>
        </p>
        <p>
            <span class="reduce"></span>
            <input type="text" value="1" class="a">
            <span class="add">+</span>
        </p>
        <p>
            <span class="reduce"></span>
            <input type="text" value="3" class="a">
            <span class="add">+</span>
        </p>
        <p>
            <span class="reduce"></span>
            <input type="text" value="4" class="a">
            <span class="add">+</span>
        </p>
    </div>

    <script>

        // 失去焦点的时候才做验证  blur / change

        //   分析：购物车的输入框里面本来就有正确的值  change


        // 数量加减的时候，需要更新data里面的值


        // 循环   绑定原始数据
        var oInps = document.querySelectorAll('.a') ;
        for(var i = 0 ; i < oInps.length ; i++) {
            oInps[i].setAttribute('data' , oInps[i].value) ;
        }

    

        var oCart = document.querySelector('.cart') ;
        oCart.onchange = function(e) {
            var e = e || event ;
            var target = e.target || e.srcElement ;
            if(target.className === 'a') {
                var n = target.value ;
                var m = target.getAttribute('data') ;
                // console.log(333);
                if(n > 0 && n % 1 === 0) {
                    // 正确的值存在data上面
                    target.setAttribute('data' , n) ;
                } else {
                    alert('输入必须是正整数') ;
                    // 改成原来的值
                    target.value = m;
                }
            }
        }




        // 键盘事件
        oCart.onkeydown = function(e) {
            var e = e || event ;
            var target = e.target || e.srcElement ;
            if(target.className === 'a') {
                // 回车确认
                if(e.keyCode === 13) {
                    target.blur() ;
                }
            }
        }

    </script>
    
</body>
</html>